package com.liang.security.springmvc.controller;

import com.liang.security.springmvc.model.AuthenticationRequest;
import com.liang.security.springmvc.model.UserDto;
import com.liang.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author liang zai
 * @date 2021/8/31 11:14
 * @description
 */
@RestController
public class LoginController {

    @Autowired
    private AuthenticationService authenticationService;

    /**
     * 用户登录
     * @param request
     * @return
     */
    @PostMapping(value = "/login", produces = {"text/plain;charset=Utf-8"})
    public String login(AuthenticationRequest request, HttpSession session) {
        UserDto authentication = authenticationService.authentication(request);
        session.setAttribute(UserDto.SESSION_USER_KEY, authentication);
        return authentication.getFullname() +"登录成功";
    }

    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=utf-8"})
    public String r1(HttpSession session) {
        String fullName = "匿名";
        Object attribute = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (attribute != null) {
            fullName = ((UserDto)attribute).getFullname();
        }
        return fullName + "访问资源1";
    }

    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=utf-8"})
    public String r2(HttpSession session) {
        String fullName = "匿名";
        UserDto userDto = (UserDto) session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userDto != null) {
            fullName = userDto.getFullname();
        }

        return fullName + "访问资源2";
    }
}
